package com.dyzx.hbb.modules.sys.service.impl;

import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dyzx.hbb.common.config.MyLambdaQueryWrapper;
import com.dyzx.hbb.modules.finance.service.FinanceOrganWalletBillService;
import com.dyzx.hbb.modules.mtn.entity.MtnOrder;
import com.dyzx.hbb.modules.mtn.entity.MtnOrderItem;
import com.dyzx.hbb.modules.mtn.service.MtnOrderItemService;
import com.dyzx.hbb.modules.mtn.service.MtnOrderService;
import com.dyzx.hbb.modules.sys.bean.SysWorkPaymentBean;
import com.dyzx.hbb.modules.sys.entity.SysWorkPayment;
import com.dyzx.hbb.modules.sys.mapper.SysWorkPaymentMapper;
import com.dyzx.hbb.modules.sys.service.SysWorkPaymentService;
import com.dyzx.hbb.modules.sys.vo.SysWorkPaymentBeanUVO;
import com.dyzx.hbb.modules.sys.vo.SysWorkPaymentBeanVO;
import com.dyzx.hbb.security.context.SecurityContextHolder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @author Administrator
 * @description 针对表【sys_work_payment(支付记录表)】的数据库操作Service实现
 * @createDate 2025-08-05 17:39:49
 */
@Service
public class SysWorkPaymentServiceImpl extends ServiceImpl<SysWorkPaymentMapper, SysWorkPayment>
        implements SysWorkPaymentService {
    @Autowired
    private MtnOrderService mtnOrderService;

    @Autowired
    private MtnOrderItemService mtnOrderItemService;

    @Autowired
    private FinanceOrganWalletBillService walletBillService;

    @Override
    public SysWorkPaymentBean getWorkPayment(Long orderId, Integer type) {
        SysWorkPayment pyData = getPayInfo(orderId, type);
        SysWorkPayment pyDataR = getPayInfoReceived(orderId, type);
        SysWorkPaymentBean data = getMptService(orderId);
       if(pyData.getDiscountAmt() == null || pyData.getDiscountAmt() == 0L){
            pyData.setDiscountAmt(data.getDiscount() == null ? 0L : data.getDiscount());
        }
        data.setPaid(pyData.getPaidAmt());
        data.setReceived(pyDataR.getPaidAmt());
        data.setDiscount(pyData.getDiscountAmt());
        data.setPending(data.getTotal() - pyData.getPaidAmt() - pyData.getDiscountAmt());
        List<Map<String, Object>> list = getPayList(orderId, type);
        if (list == null) {
            list = new ArrayList<>();
        }
        data.setList(list);
        return data;
    }

    @Override
    public boolean savePayment(SysWorkPaymentBeanVO vo) {
        Long organId = SecurityContextHolder.getOrganId();
        Long userId = SecurityContextHolder.getUserId();
        SysWorkPaymentBean workPayment = getWorkPayment(vo.getOrderId(), vo.getType());
        if (workPayment.getPending() >= vo.getMoney()) {
            SysWorkPayment payment = new SysWorkPayment();
            payment.setPaymentMethod(vo.getPaymentMethod());
            payment.setOrderId(vo.getOrderId());
            payment.setTotalAmt(workPayment.getTotal());
            payment.setPaidAmt(vo.getMoney());
            payment.setTargetId(vo.getType());
            payment.setState(vo.getState());
            payment.setOperatorId(userId);
            payment.setOrganId(organId);
            boolean save = this.save(payment);
            if (save) {
                if (workPayment.getPending() == 0) {
                    paidUpdate(vo.getOrderId(), vo.getType());
                }
            }
            return save;
        } else {
            return false;
        }

    }

    @Override
    public boolean endPayment(SysWorkPaymentBeanUVO vo) {
        Integer type = vo.getType();
        Long orderId = vo.getOrderId();
        SysWorkPaymentBean workPayment = getWorkPayment(vo.getOrderId(), vo.getType());

        boolean flag = false;
        switch (type) {
            case 1:
                MtnOrder order = mtnOrderService.getById(orderId);
                boolean isPaid=workPayment.getIsPaid()==2;
                if(isPaid) {

                    order.setStatus(3);
                }else{
                    order.setStatus(2);
                }
                flag = mtnOrderService.updateById(order);
                if (flag) {
                    boolean a=   inWalletBill(orderId,type,workPayment.getPaid(),workPayment.getPending(),isPaid);
                }

                break;
            default:
                break;
        }
        return flag;
    }

    @Override
    public boolean updateWorkItemDiscount(Long workId, Long orderId, Long itemId, Long discountId, Long amt) {
        MtnOrderItem item = mtnOrderItemService.getById(itemId);
        item.setDiscountId(discountId);
        item.setDiscountAmt(amt);
        boolean update = mtnOrderItemService.updateById(item);
        if( update){
            List<MtnOrderItem> list = mtnOrderItemService.list(new MyLambdaQueryWrapper<MtnOrderItem>().eq(MtnOrderItem::getOrderId, item.getOrderId()));
            System.out.println("list"+list);

            Long reduce = list.stream().map(MtnOrderItem::getTotalAmt).reduce(0L, Long::sum);
            Long discount = list.stream().map(item1 -> item1.getDiscountAmt() == null ? 0L : item1.getDiscountAmt()).reduce(0L, Long::sum);
            MtnOrder order = new MtnOrder();
            order.setId(item.getOrderId());
            order.setTotalAmt(reduce);
            order.setDiscountAmt(discount);
          boolean f=  mtnOrderService.updateById(order);
            if(!f){
                System.out.println("更新订单项目优惠金额失败");
            }
            return true;
        }
        return false;
    }

    private boolean inWalletBill(Long orderId, Integer type, Long paid, Long pending, boolean isPaid) {
        return walletBillService.inWalletBill(orderId,type,paid,pending,isPaid);
    }



    private boolean paidUpdate(long orderId, Integer type) {
        Long organId = SecurityContextHolder.getOrganId();
        boolean flag = false;
        switch (type) {
            case 1:
                LambdaUpdateWrapper<MtnOrder> wrapper = new LambdaUpdateWrapper<>();
                wrapper.eq(MtnOrder::getId, orderId).eq(MtnOrder::getOrganId, organId);

                wrapper.eq(MtnOrder::getIsPaid, 2);
                flag = mtnOrderService.update(wrapper);
                break;
            case 2:
                break;
            case 3:
                break;
            default:
                break;
        }
        return flag;
    }

    private List<Map<String, Object>> getPayList(Long orderId, Integer type) {
        Long organId = SecurityContextHolder.getOrganId();
        MyLambdaQueryWrapper<SysWorkPayment> wrapper = new MyLambdaQueryWrapper<>();
        wrapper.eq(SysWorkPayment::getOrderId, orderId).eq(SysWorkPayment::getTargetId, type).eq(SysWorkPayment::getOrganId, organId);
        wrapper.select(SysWorkPayment::getId, SysWorkPayment::getOrderId, SysWorkPayment::getTargetId, SysWorkPayment::getTotalAmt,
                SysWorkPayment::getPaidAmt, SysWorkPayment::getDiscountAmt, SysWorkPayment::getState, SysWorkPayment::getPaymentMethod,
                SysWorkPayment::getCreateDate, SysWorkPayment::getUpdateDate);
        return this.listMaps(wrapper);
    }

    private SysWorkPayment getPayInfo(Long orderId, Integer type) {
        Long organId = SecurityContextHolder.getOrganId();
        MyLambdaQueryWrapper<SysWorkPayment> wrapper = new MyLambdaQueryWrapper<>();
        wrapper.eq(SysWorkPayment::getOrderId, orderId).eq(SysWorkPayment::getTargetId, type).eq(SysWorkPayment::getOrganId, organId);
        wrapper.sum(SysWorkPayment::getPaidAmt).as("paid_amt");
        wrapper.sum(SysWorkPayment::getDiscountAmt).as("discount_amt");
        wrapper.eq(SysWorkPayment::getState, 1);
        wrapper.groupBy(SysWorkPayment::getOrderId, SysWorkPayment::getTargetId);
        wrapper.last("limit 1");
        SysWorkPayment one = getOne(wrapper);
        if (one == null) {
            one = new SysWorkPayment();
            one.setPaidAmt(0L);
            one.setDiscountAmt(0L);
        }
        return one;
    }

    private SysWorkPayment getPayInfoReceived(Long orderId, Integer type) {
        Long organId = SecurityContextHolder.getOrganId();
        MyLambdaQueryWrapper<SysWorkPayment> wrapper = new MyLambdaQueryWrapper<>();
        wrapper.eq(SysWorkPayment::getOrderId, orderId).eq(SysWorkPayment::getTargetId, type).eq(SysWorkPayment::getOrganId, organId);
        wrapper.sum(SysWorkPayment::getPaidAmt).as("paid_amt");
        wrapper.eq(SysWorkPayment::getState, 2);
        wrapper.last("limit 1");
        wrapper.groupBy(SysWorkPayment::getOrderId, SysWorkPayment::getTargetId);
        SysWorkPayment one = getOne(wrapper);
        if (one == null) {
            one = new SysWorkPayment();
            one.setPaidAmt(0L);
            one.setDiscountAmt(0L);
        }
        return one;
    }

    private SysWorkPaymentBean getMptService(Long orderId) {
        SysWorkPaymentBean data = new SysWorkPaymentBean();
        MtnOrder byId = mtnOrderService.getById(orderId);
        System.out.println(byId);
        data.setTotal(byId.getTotalAmt());
        data.setDiscount(byId.getDiscountAmt());
        data.setIsPaid(byId.getIsPaid());
        return data;
    }
}




